package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"tie/api/register"
	"tie/initlist/cache"
	"tie/initlist/mysql"
	"tie/inits/model"
	"tie/pkg"
	"time"
)

func TieAdd(r *gin.Context) {
	var req register.Tie
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}
	rabbitmq := pkg.NewRabbitMQSimple("yyq")
	rabbitmq.PublishSimple("Hello kuteng222!")
	fmt.Println("发送成功！")

	tie := model.Tie{
		Title:   req.Title,
		Name:    req.Name,
		Quan:    req.Quan,
		Status:  req.Status,
		Guan:    req.Guan,
		Hotspot: req.Hotspot,
		Hot:     req.Hot,
	}
	mysql.DB.Debug().Create(&tie)
	r.JSON(200, &Res{
		Code:    200,
		Message: "帖子发布成功",
		Data:    tie,
	})
}

func TieList(r *gin.Context) {
	var req register.Tie
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}

	var all []model.Tie
	mysql.DB.Debug().Order("hot ASC").Find(&all)
	r.JSON(200, &Res{
		Code:    200,
		Message: "帖子列表成功",
		Data:    all,
	})
}

func TieShow(r *gin.Context) {
	var req register.Tie
	err := r.ShouldBind(&req)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数失败",
			Data:    nil,
		})
		return
	}
	key := fmt.Sprintf("tie_show")
	result, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &req)
	} else {
		marshal, _ := json.Marshal(req)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*5)
	}
	var show []model.Tie
	mysql.DB.Debug().Find(&show)
	r.JSON(200, &Res{
		Code:    200,
		Message: "详情展示成功",
		Data:    show,
	})
}
